  <!-- 角色管理 -->
<template>
  <div class="main-body">
    <header class="main-body-search">
      <el-form :model="search" @submit.native.prevent>
        <el-row :gutter="50" type="flex" justify="space-between">
          <el-col :span="12">
            <el-button type="primary" @click="showDetail({})" icon="el-icon-plus">新建角色</el-button>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-form-item label class="nja-form-line">
              <el-input
              style="width: 300px;"
                v-model.trim="search.role"
                placeholder="角色名称"
                clearable
                @keyup.enter.native="searchHandle"
              >
              <div  slot="prefix" style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;">
                <i class="el-icon-search"></i>
              </div>
              <el-button type="primary" slot="append" @click="searchHandle">查询</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </header>
    <el-main class="main-body-table">
      <div class="table-shadow"></div>
      <el-table :data="tableData" stripe style="width: 100%" height="calc(100vh - 250px)">
        <!-- <el-table-column prop="id" label="角色ID" align="center" width="180"></el-table-column> -->
        <el-table-column prop="role" label="角色名称" align="center" width="180"></el-table-column>
        <el-table-column prop="roleDesc" show-overflow-tooltip label="描述" align="center"></el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="lastUpdateTime" label="更新时间" align="center"></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="160px">
          <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="showDetail(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" v-if="scope.row.isdef != 1" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"></el-empty>
        </template>
      </el-table>
      <!--工具条-->
      <el-pagination
        background
        class="main-body-table-page"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        :current-page="search.current"
        :page-size="search.size"
        :total="search.total"
      ></el-pagination>
    </el-main>
    <el-dialog
      :title="form.id ? '编辑角色' : '新增角色'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      center
      v-dialogDrag
      custom-class="mydialog"
      width="700px"
    >
      <el-form ref="form" class="formlayout" :model="form" label-width="90px" label-position="left">
        <el-form-item
          class="dccform-line"
          label="角色名称"
          prop="role"
          required
          :rules="[{required: true, message: '必填'}]"
        >
          <el-input v-model="form.role" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item
          class="dccform-line"
          label="角色描述"
          prop="roleDesc"
        >
          <el-input v-model="form.roleDesc" type="textarea" maxlength="200" placeholder="请输入角色描述"></el-input>
        </el-form-item>
        <el-form-item
          class="dccform-line"
          label="应用菜单"
        >
        </el-form-item>
        <el-tabs tab-position="left" v-model="activeApp" @tab-click="appChange">
          <el-tab-pane :label="app.appName" :name="app.id" v-for="(app, i) in apps" :key="i">
            <el-tree :ref="`MenuRef${app.id}`" :data="menu" show-checkbox check-strictly node-key="id" @check="checkMenu" :default-expand-all="true" :props="defaultProps"></el-tree>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" style="width: 120px;" @click="saveHandle">保存</el-button>
        <el-button style="width: 120px;" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { SelectPageRole, SaveRole, DeleteRole, GetRoleMenu, GetAllMenu } from '@/api'
import {
    SelectList
  } from '@/api/admin/app'
import {toTree} from '@/util/common.js'
export default {
  data() {
    return {
      dialogVisible: false,
      search: {
        current: 1,
        size: 20,
        total: 0,
        role: ''
      },
      form: {
        id: '',
        role: '',
        roleDesc: ''
      },
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      activeApp: '',
      apps: [],
      appMap: {},
      menuids: [],
      tableData: []
    }
  },
  computed: {
    menu () {
      let menus = this.menuData.filter(d => d.appId == this.activeApp)
      return toTree(menus)
    }
  },
  methods: {
    checkMenu (row, {checkedKeys}) {
      console.log('checkMenu', row, checkedKeys)
      this.menuids = [...checkedKeys, ...this.menuids.filter(d => d.indexOf(this.activeApp) != 0)]
    },
    appChange () {
      this.$nextTick(() => {
        this.$refs[`MenuRef${this.activeApp}`][0].setCheckedKeys(this.menuids)
      })
    },
    loadApps() {
      return SelectList().then(res => {
        if (res.code === 20000) {
          let map = {}
          this.apps = res.data.filter(d => d.needlogin == 1).map(d => {
            map[d.id] = d
            return d
          })
          this.appMap = map
        }
      })
    },
    loadMenu () {
      return GetAllMenu().then(res => {
        if (res.code === 20000) {
          let appids = [...new Set(res.data.map(d => d.appId))]
          let temp = res.data
          this.apps.forEach(d => {
            if (!appids.includes(d.id)) {
              // 不存在的菜单
              temp.push(
                {
                id: `${d.id}_Def`,
                appId: d.id,
                menuUri: `${d.id}_index`,
                menuName: '默认页'
              }
              )
            } 
          })
          this.menuData = temp
          console.log('======', this.menuData)
        }
      })
    },
    showDetail(row) {
      this.form = Object.assign(
        {
          id: '',
          role: '',
          roleDesc: ''
        },
        row
      )
      this.menuids = []
      this.dialogVisible = true
      if (this.apps && this.apps.length > 0) {
        this.activeApp = this.apps[0].id
      }
      this.$nextTick(() => {
        this.$refs[`MenuRef${this.activeApp}`][0].setCheckedKeys([])
        this.$refs.form.clearValidate()
        if (row.id) {
          this.getRoleMenu(row.id)
        }
      })
    },
    getRoleMenu (roleId) {
      GetRoleMenu({roleId}).then(res => {
        console.log('GetRoleMenu', res)
        if (res.code === 20000) {
          this.menuids = res.data.map(d => {
            let m = this.menuData.find(j => j.menuUri == d.menu)
            if (m) {
              return m.id
            }
            return ''
          }).filter(d => d)
          console.log(this.menuids)
          this.$nextTick(() => {
            this.$refs[`MenuRef${this.activeApp}`][0].setCheckedKeys(this.menuids)
          })
        }
      })
    },
    deleteRow(row) {
      console.log(row)
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteRole({ id: row.id }).then((res) => {
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.loadData()
          }
        })
      })
    },
    saveHandle() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 保存
          let params = Object.assign({}, this.form)
          delete params.lastUpdateTime
          delete params.createTime
          params.menus =  this.menuData.filter(j =>  this.menuids.includes(j.id))
          SaveRole(params).then((res) => {
            console.log('SaveRole', res)
            if (res.code === 20000) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.dialogVisible = false
              this.loadData()
            }
          })
        }
      })
    },
    handleCurrentChange(val) {
      this.search.current = val
      this.loadData()
    },
    searchHandle() {
      this.search.current = 1
      this.loadData()
    },
    loadData() {
      SelectPageRole(this.search)
        .then((res) => {
          console.log('success:', res)
          this.tableData = res.data.records
          this.search.total = res.data.total
        })
        .catch((err) => {
          console.log('err:', err)
        })
    }
  },
  async mounted() {
    await this.loadApps()
    this.loadMenu()
    this.loadData()
  }
}
</script>

<style lang="scss" scoped>
.tableimg {
  width: 45px;
}
.formlayout {
  padding: 20px 40px;
}

</style>
